using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.Security.Permissions;
using MagnoliaTableAdapters;


public partial class ReportMakeGoods : System.Web.UI.Page
{
    static DataTable dtResults = new DataTable();
    static string pageResultStr = "";
    static string reportResultStr = "";

    protected override void Render(HtmlTextWriter writer)
    {
        // Write the HTML into this string builder
        StringBuilder sb = new StringBuilder();
        HtmlTextWriter hWriter = new HtmlTextWriter(new StringWriter(sb));
        base.Render(hWriter);

        // Store to a string
        pageResultStr = sb.ToString();

        // Write it back to the server's HTTP Stream -// *** skip this if you don't want to display the rendered content
        writer.Write(pageResultStr);
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Reporting - Make Goods";
        
        // Add calendar to date fields
        TextBox_DateFrom.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateFrom.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");

        Btn_RunReport.Attributes.Add("onfocus", "cs_blur();");
        Btn_Reset.Attributes.Add("onfocus", "cs_blur();");
        Btn_Print.Attributes.Add("onclick", "window.print();");
        Btn_ExportCSV.Attributes.Add("onclick", "showExportPopup();");

        Lbl_Messages.Text = "Please provide your report parameters and click \"Run Report\" to view the results";

        if (!Page.IsPostBack)
        {
            ExportFileName.Value = Convert.ToString(Page.Title) + ".doc";

            // Load client list
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
            try
            {
                // Open connection to db
                conn.Open();

                string sProc = "sproc_WEB_GetListClient";
                SqlCommand cmd = new SqlCommand(sProc, conn);
                cmd.CommandType = CommandType.StoredProcedure;

                // execute the stored procedure and return the results
                DataTable dtClients = new DataTable();
                SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
                sqlAdapter.Fill(dtClients);

                if (dtClients.Rows.Count > 0)
                {
                    DDList_Clients.DataSource = dtClients;
                    DDList_Clients.DataTextField = Convert.ToString(dtClients.Columns[1]);
                    DDList_Clients.DataValueField = Convert.ToString(dtClients.Columns[0]);
                    DDList_Clients.DataBind();

                    //ListItem defaultItem = new ListItem();
                    //defaultItem.Value = "0";
                    //defaultItem.Text = "Select...";
                    //DDList_Clients.Items.Insert(0, defaultItem);
                    //DDList_Clients.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
    }

    protected void Btn_RunReport_Click(object sender, EventArgs e)
    {
        Lbl_Alerts.Visible = false;
        Lbl_ClientName.Visible = false;
        Lbl_Messages.Visible = false;
        GridView_Results.Visible = false;

        if ( (TextBox_DateFrom.Text.Trim().Length == 0)
                || (TextBox_DateTo.Text.Trim().Length == 0))
        {
            Lbl_Alerts.Text = "Please fill out all report parameters";
            Lbl_Alerts.Style.Add("color", "Red");
            Lbl_Messages.Text = "Please provide your report parameters and click \"Run Report\" to view the results";
            Lbl_Messages.Visible = true;
            Lbl_Alerts.Visible = true;
            return;
        }

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            // Open connection to db
            conn.Open();

            string sProc = "sproc_WEB_ReportMakeGoods";
            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@ClientID";
            param.Value = Convert.ToInt32(DDList_Clients.SelectedValue);
            param.DbType = DbType.Int32;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateStart";
            param.Value = Convert.ToDateTime(TextBox_DateFrom.Text);
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateEnd";
            param.Value = Convert.ToDateTime(TextBox_DateTo.Text);
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            //DataTable dtResults = new DataTable();
            dtResults.Columns.Clear();
            dtResults.Rows.Clear();

            SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
            sqlAdapter.Fill(dtResults);
            
            conn.Close();

            if (dtResults.Rows.Count == 0)
            {
                Lbl_Messages.Text = "The given report parameters returned no results";
                Lbl_Messages.Visible = true;
                Btn_Print.Enabled = false;
                Btn_ExportCSV.Enabled = false;
                GridView_Results.Visible = false;
            }
            else
            {
                Lbl_ClientName.Text = "Client: " + Convert.ToString(DDList_Clients.SelectedItem.Text);
                Lbl_ClientName.Visible = true;
                GridView_Results.DataSource = dtResults;
                GridView_Results.DataBind();
                GridView_Results.Visible = true;

                // get and display totals
                int timesPlayedTotal = 0;
                decimal totalMinutesTotal = 0;
                for (int i = 0; i < GridView_Results.Rows.Count; i++)
                {
                    timesPlayedTotal += Convert.ToInt32(GridView_Results.Rows[i].Cells[2].Text);
                    totalMinutesTotal += Convert.ToDecimal(GridView_Results.Rows[i].Cells[3].Text);
                }
                GridView_Results.FooterRow.Cells[1].Style["text-align"] = "right";
                GridView_Results.FooterRow.Cells[1].Text = "Totals:";
                GridView_Results.FooterRow.Cells[2].Text = Convert.ToString(timesPlayedTotal);
                GridView_Results.FooterRow.Cells[3].Text = Convert.ToString(totalMinutesTotal);

                Lbl_Messages.Visible = false;
                Btn_Print.Enabled = true;
                Btn_ExportCSV.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            //Utilities.SendErrorLogEmail(ex);  WGO: !!! Unable to find library
            String err = ex.Message;
        }
        finally
        {
            conn.Close();
        }

    }
    protected void Btn_Reset_Click(object sender, EventArgs e)
    {
        DDList_Clients.SelectedIndex = -1;
        TextBox_DateFrom.Text = "";
        TextBox_DateTo.Text = "";
        Lbl_Alerts.Visible = false;
    }
    protected void ExportGridToCSV()
    {
        // Create the CSV file to which grid data will be exported
        String FileName = Convert.ToString(Page.Title) + ".csv";
        String ExportPath = Server.MapPath("Exports");
        String FilePath = ExportPath + "\\" + FileName;
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        StreamWriter sw = new StreamWriter(FilePath, false);
        // First we will write the headers.
        int iColCount = dtResults.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dtResults.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
        // Now write all the rows.
        foreach (DataRow dr in dtResults.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

    protected void WriteReportToFile()
    {
        // Create the file to which data will be exported
        String FileName = Convert.ToString(Page.Title) + ".doc";
        String ExportPath = Server.MapPath("Exports");
        String FilePath = ExportPath + "\\" + FileName;
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        StreamWriter sw = new StreamWriter(FilePath, false);

        // Get Report From Page string
        String startIndexStr = "<div class=\"reportResults\">";
        String endIndexStr = "</table>";

        int startIndex = pageResultStr.IndexOf(startIndexStr);
        int endIndex = pageResultStr.IndexOf(endIndexStr);
        reportResultStr = pageResultStr.Substring(startIndex, endIndex - startIndex + 8);
        reportResultStr += "</div></div>";

        sw.Write(reportResultStr);
        sw.Close();
    }

    protected void Btn_ExportCSV_Click(object sender, EventArgs e)
    {
        WriteReportToFile();
        //ExportGridToCSV();
    }
}
